package cn.edu.bupt.freewings.forum.front.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.bupt.freewings.forum.common.PostType;
import cn.edu.bupt.freewings.forum.common.UserType;
import cn.edu.bupt.freewings.forum.common.ProjectType;
import cn.edu.bupt.freewings.forum.client.rest.PostClient;
import cn.edu.bupt.freewings.forum.front.Constants;
import cn.edu.bupt.freewings.forum.front.beans.UserBean;

/**
 * @author hubaiyu (hubaiyu@gmail.com)
 *
 */
public class NewPostAction extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		UserBean user = (UserBean)request.getSession().getAttribute(Constants.USER);
		if(user == null){
			response.sendRedirect("login.jsp");
			return;
		}
		int topicId = Integer.valueOf(request.getParameter("id"));
		String text = request.getParameter("text");
		PostType.Post post = makePost(text, topicId, user.getId());
		new PostClient().put(post);
		response.sendRedirect("topic?id=" + topicId);
	}
	
	static PostType.Post makePost(String text, Integer topicId, Integer userId){
		PostType.Post.Builder builder = PostType.Post.newBuilder();
		builder.setText(text).setTopicId(topicId).setUserId(userId).setPostTime(System.currentTimeMillis());
		return builder.build();
	}
}